package com.wq.myspring.resource;

import org.springframework.core.io.FileSystemResource;

import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName: com.wq.myspring.resourcetest
 * @ClassName MyResource
 * @Description: TODO
 * @Author Wenqiang
 * @Date 2021/07/17 9:53
 * @Version V1.0
 */
public class MyResource {

	public static void main(String[] args) throws IOException, InterruptedException {
		// ClassPathResource在环境变量中读取配置文件
		//ClassPathResource resource = new ClassPathResource("test.txt");

		//FileSystemResource 需要给出文件的相对或者绝对路径
		// FileSystemResource resource = new FileSystemResource("application-test/src/main/resources/test.txt");
		// File file = resource.getFile();
		// System.out.println(file.length());



		Lock lock = new ReentrantLock();
		new Thread(() -> {
			lock.lock();
			FileSystemResource resource = getResource("application-test/src/main/resources/test.txt");
			try(InputStream inputStream = resource.getInputStream();) {
				byte[] b = new byte[1024];
				while(inputStream.read(b, 0, b.length) != -1) {
					System.out.println(new String(b));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}, "Thread-01-input").start();

		TimeUnit.SECONDS.sleep(1);

		new Thread(() -> {
			lock.lock();
			FileSystemResource resource = getResource("application-test/src/main/resources/test.txt");
			try (OutputStream outputStream = resource.getOutputStream();
				 BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
			) {
				bufferedWriter.write("你好，中国");
				bufferedWriter.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}, "Thread-02-output").start();

	}

	//获取Resource实例 ("application-test/src/main/resources/test.txt")
	public static FileSystemResource getResource(String path) {
		FileSystemResource resource = new FileSystemResource(path);
		if (null != resource) {
			return resource;
		}
		return null;
	}





}
